package com.baitiaojun.security.core.domain;

import cn.hutool.core.collection.CollectionUtil;
import com.baitiaojun.security.core.serializer.AuthorityDeserializer;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 登陆模型
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class LoginUser implements UserDetails {

    /**
     * 租户ID
     */
    private String tenant;

    /**
     * 用户ID
     */
    private Long userId;

    /**
     * 部门ID
     */
    private Long deptId;

    /**
     * 用户唯一标识
     */
    private String token;

    /**
     * 登录时间
     */
    private Long loginTime;

    /**
     * 过期时间
     */
    private Long expireTime;

    /**
     * 登录IP地址
     */
    private String ipaddr;

    /**
     * 登录地点
     */
    private String loginLocation;

    /**
     * 浏览器类型
     */
    private String browser;

    /**
     * 操作系统
     */
    private String os;

    /**
     * 权限列表
     */
    private Set<String> permissions;

    /**
     * 用户信息
     */
    private UserInfo userInfo;

    /**
     * 用户权限, 定义权限属性,添加set方法,防止redis反序列化报错
     */
    private Collection<? extends GrantedAuthority> authorities;


    public LoginUser(UserInfo userInfo, Set<String> permissions) {
        this.userInfo = userInfo;
        this.permissions = permissions;
    }

    /**
     * 设置用户权限
     * @return
     */
    @JsonDeserialize(using = AuthorityDeserializer.class)
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        if (CollectionUtil.isEmpty(permissions)) {
            permissions = new HashSet<>();
        }
        return permissions.stream().map(MyGrantedAuthority::new).collect(Collectors.toSet());
    }

    public void setAuthorities(Collection<? extends GrantedAuthority> authorities) {
        this.authorities = authorities;
    }

    /**
     * 设置用户密码
     * @return
     */
    @JsonIgnore
    @Override
    public String getPassword() {
        return userInfo.getPassword();
    }

    /**
     * 设置用户名
     * @return
     */
    @JsonIgnore
    @Override
    public String getUsername() {
        return userInfo.getUserName();
    }

    @JsonIgnore
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @JsonIgnore
    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @JsonIgnore
    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @JsonIgnore
    @Override
    public boolean isEnabled() {
        return true;
    }
}
